import React, {memo, useEffect, useState} from 'react';
import {Link, Redirect} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import {message, Upload} from "antd";

import './home.css';
import {checkUser, saveLanguage} from "../login/store/actionCreators";
import {saveNavigationIndex} from "../../components/navigation/store/actionCreators";
import {BASE_URL} from "../../services/config";
import {saveTargetSelectedArr} from "../main/analysis/components/quantification/store/actionCreators";
import {saveAnalysisShowLineArr, saveEndogenousControlTarget, saveGroup, saveReferenceSample} from "../main/plate/store/actionCreators";
import {saveData} from "../main/store/actionCreators";
import {getAnalysisInfo, getCurrentTime, getScanChannel, modifyData, getProtocolChannel, calCqMean, calQuantityMean} from "../../common/utils";
import {LINE_OBJ} from "../main/plate/config";
import {saveRunTargetSelectedArr} from "../main/run/components/realtimeCurve/store/actionCreators";
import {saveMeltData, savePcrData} from "../main/run/store/actionCreators";
import request from "../../services/request";
import {THRESHOLD,CUSTOM_THRESHOLD} from "../main/store/constants";
import {useChangeCoordinate} from "../../common/myHooks";
import {saveChartOption, saveExperimentSetting, saveTableData} from "../main/analysis/components/geneExpression/store/actionCreators";
import {saveIsLoad} from "../main/calculation/components/quantification/store/actionCreators";
import {AMPLIFICATION, HOLD} from "../main/protocol/config";

export default memo(function Home(props) {
  const dispatch = useDispatch();
  const {isUser, userInfo, data, isCN, isLoadDone} = useSelector(state => ({
    isUser: state.loginReducer.isUser,  //  判断是否登陆
    userInfo: state.loginReducer.info,  //  获得用户信息
    data: state.dataReducer.data,
    isCN: state.languageReducer.isCN,
    isLoadDone: state.calculationReducer.isLoad
  }));
  const [showProgress, setProgress] = useState(false);
  const [lineWidth, setLineWidth] = useState("5vw");
  const changeCoordinate = useChangeCoordinate();

  useEffect(() => {
    let lineData = getAnalysisInfo(data);
    dispatch(saveTargetSelectedArr([...new Set(lineData.targetSelectedArr)]));
    // console.log(lineData);
  }, [data]);

  const config = {
    name: 'file',
    showUploadList: false,
    action: `${BASE_URL}/uploadAction/upload`,
    headers: {
      authorization: 'authorization-text'
    },
    accept: ".cqa",
    onChange(info) {
      if (info.file.status === 'done') {
        let loadData = JSON.parse(info.file.response.data); //  加载文件后返回的数据
        loadData.experimentName = info.file.name.split(".")[0];
        changeCoordinate(loadData);
        dispatch(savePcrData(loadData.pcrDataOrigin));
        dispatch(saveMeltData(loadData.meltDataOrigin));
        let dataAfterModified = modifyData(loadData);  //  处理后的数据
        dispatch(saveTargetSelectedArr([...new Set(dataAfterModified.targetSelectedArr)]));
        dispatch(saveRunTargetSelectedArr([...new Set(dataAfterModified.targetSelectedArr)]));
        dispatch(saveAnalysisShowLineArr(dataAfterModified.analysisShowLineArr));
        dispatch(saveEndogenousControlTarget(dataAfterModified.endogenousControlTarget));
        dispatch(saveReferenceSample(""));
        dispatch(saveExperimentSetting(dataAfterModified.experimentSetting));
        dispatch(saveTableData([]));
        dispatch(saveChartOption({}));
        let groupWellList = loadData.wells.filter(well => well.groupUuid !== '' && well.groupColor !== '');
        let arr = [], obj = {};
        groupWellList.forEach(item => {
          if (obj.hasOwnProperty(item.groupName)) {

          } else {
            obj[item.groupName] = item.groupName;
            arr.push({
              uuid: item.groupUuid,
              opt: false,
              name: item.groupName,
              color: item.groupColor,
              comments: ""
            });
          }
        });
        dispatch(saveGroup(arr));
        request({
          url: 'analysis/calAll',
          data: {...dataAfterModified.loadData, analysisMethodSetting: {...dataAfterModified.loadData.analysisMethodSetting, mode: CUSTOM_THRESHOLD}},
          method: 'post'
        })
          .then(res => {
            switch (res.code) {
              case 200:
                //  保存data
                calCqMean(res.data);
                calQuantityMean(res.data);
                dispatch(saveData(res.data));
                break;
              case 500:
                message.error(res.message);
                break;
              default:
                message.error("error");
                // TODO: 排查错误
                console.log(res);
            }
          })
          .catch(err => message.error(err));
        loadingToAnalysis();
        isCN
          ? message.success(`${info.file.name} 加载成功`)
          : message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        isCN
          ? message.success(`${info.file.name} 加载失败`)
          : message.error(`${info.file.name} file upload failed.`);
      }
    }
  };
  const experimentConfig = {
    name: 'file',
    showUploadList: false,
    action: `${BASE_URL}/uploadAction/upload`,
    headers: {
      authorization: 'authorization-text'
    },
    accept: ".cqa",
    onChange(info) {
      if (info.file.status === 'done') {
        dispatch(saveIsLoad(true));
        let loadData = JSON.parse(info.file.response.data); //  加载文件后返回的数据
        loadData.experimentName = getCurrentTime();
        loadData.wells.forEach(item => item.lines = [{...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}]);
        dispatch(saveData(loadData));
        loadingToRun();
        isCN
          ? message.success(`${info.file.name} 加载成功`)
          : message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        isCN
          ? message.success(`${info.file.name} 加载失败`)
          : message.error(`${info.file.name} file upload failed.`);
      }
    }
  };

  //  切换语言
  function changeLanguage() {
    dispatch(saveLanguage(!isCN));
    //TODO:关掉客户端不清掉缓存，重新刷新进入保留原有中英文的的状态
    localStorage.removeItem('isCN');
    localStorage.setItem('isCN', JSON.stringify(!isCN));
  }

  //  退出登陆
  function loginOut() {
    dispatch(checkUser(false));
    message.info("exit");
  }

  function loadingToMain() {
    /*
     初始化protocol的通道以setting为主
     */
    let data_channels = getProtocolChannel().channel;
    // console.log(data_channels, getProtocolChannel());
    dispatch(saveData({
      ...data,
      connectPort: "",
      protocol: {...data.protocol, channels: data_channels}
    }));
    dispatch(saveNavigationIndex(0));
    setProgress(true);
    let progressWidth = 10;
    let line = setInterval(() => {
      setLineWidth(progressWidth + "vw");
      progressWidth += 10;
      if (progressWidth > 40) {
        clearInterval(line);
        setTimeout(() => {
          setProgress(false);
          props.history.push("/main");
        }, 200);
      }
    }, 600);
  }

  function loadingToAnalysis() {
    dispatch(saveNavigationIndex(4));
    setProgress(true);
    let progressWidth = 10;
    let line = setInterval(() => {
      setLineWidth(progressWidth + "vw");
      progressWidth += 10;
      if (progressWidth > 40) {
        clearInterval(line);
        setTimeout(() => {
          setProgress(false);
          props.history.push("/main/analysis");
        }, 200);
      }
    }, 600);
  }

  function loadingToRun() {
    dispatch(saveNavigationIndex(3));
    setProgress(true);
    let progressWidth = 10;
    let line = setInterval(() => {
      setLineWidth(progressWidth + "vw");
      progressWidth += 10;
      if (progressWidth > 40) {
        clearInterval(line);
        setTimeout(() => {
          setProgress(false);
          props.history.push("/main/run");
        }, 200);
      }
    }, 600);
  }

  return isUser ? (
    <div className="home">
      <div className="homeUser">
        {
          userInfo.portrait ? <div style={{backgroundImage: `url(${userInfo.portrait})`}}/> : <div/>
        }
        <div>{isCN ? "你好" : "Hello"}</div>
        <div>{userInfo.username}</div>
      </div>
      <div onClick={changeLanguage} className="language">{isCN ? "English" : "中文"}</div>
      <div className="title">cqMAN</div>
      <div className="subtitle">{isCN ? "荧光定量PCR云数据处理和分析软件" : "Cloud qPCR Management & Analysis Software"}</div>
      {
        /* 进度条展示 */
        showProgress ? <div className="homeProgress">
            <div>{isCN ? "加载中..." : "Loading..."}</div>
            <div/>
            <div style={{width: lineWidth}}/>
          </div> :
          <ul className="navbar">
            <li>
              <Link onClick={e => {
                e.preventDefault();
                loadingToMain();
              }} to="/#">  {/* a标签本身有事件,需要先阻止默认事件后才能跳转*/}
                <div className="bgNewExperiment"/>
                <div style={{marginTop: isCN ? 45 : null}}>{isCN ? "新实验" : "New Experiment"}</div>
              </Link>
            </li>
            <li>
              <Upload {...experimentConfig}>
                <a id="load" href="/#"
                   onClick={e => e.preventDefault()}
                >
                  <div className="bgLoadExperiment"/>
                  <div style={{marginTop: isCN ? 45 : null}}>{isCN ? "调用实验" : "Load Experiment"}</div>
                </a>
              </Upload>
            </li>
            <li>
              <Upload {...config}>
                <a id="load" href="/#"
                   onClick={e => e.preventDefault()}
                >
                  <div className="bgDataAnalysis"/>
                  <div style={{marginTop: isCN ? 45 : null}}>{isCN ? "数据分析" : "Data Analysis"}</div>
                </a>
              </Upload>
            </li>
            <li>
              <Link to="/setting"
                    onClick={() => dispatch(saveNavigationIndex(0))}
              >
                <div className="bgSetting" style={{height: "129px"}}/>
                <div>{isCN ? "设置" : "Setting"}</div>
              </Link>
            </li>
            <li>
              <Link to="/about">
                <div className="bgAbout" style={{height: "129px"}}/>
                <div>{isCN ? "关于" : "About"}</div>
              </Link>
            </li>
          </ul>
      }
      <div className="homeOut" onClick={loginOut}>
        {isCN ? "退 出" : "Sign Out"}
      </div>
    </div>
  ) : (
    <Redirect to="/"/>
  );
});
